import 'package:blocks_blkk/components/return_button.dart';
import 'package:blocks_blkk/page/entity/local_constants.dart';
import 'package:blocks_blkk/page/program.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'entity/devcie_entity.dart' as device;
import 'entity/program_entity.dart';
// import 'program_v20.dart';
// import 'program_v30.dart';
// import 'program_v40.dart';
// import 'program_v60.dart';
// import 'program_v70.dart';

//编程入口
class ProgramEntry extends StatefulWidget {
  final device.DeviceEntity deviceEntity;

  const ProgramEntry({super.key, required this.deviceEntity});
  @override
  _ProgramEntryState createState() => _ProgramEntryState();
}

class _ProgramEntryState extends State<ProgramEntry> {
  int _selectIndex = -1;
  List<ProgramEntity> programEntryList = [];
  // final DeviceEntity deviceEntity;

  // _ProgramEntryState();

  @override
  void initState() {
    super.initState();
    // programEntryList =
    //     ProgramEntity.loadAll(filename: widget.deviceEntity.name);
  }

  TextStyle _titleStyle = const TextStyle(color: Colors.white, fontSize: 11);
  @override
  Widget build(BuildContext context) {
    if (programEntryList == null) {
      //加载所有ProgramEntity
      // programEntryList =
      //     ProgramEntity.loadAll(filename: widget.deviceEntity.name);
      _titleStyle =
          Theme.of(context).textTheme.bodyMedium!.apply(color: Colors.white);
    }

    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
            image: AssetImage('assets/background.png'), fit: BoxFit.fill),
      ),
      child: Container(
          child: Stack(
        children: <Widget>[ReturnButton(), _deleteBtn(context), _programArea()],
      )),
    );
  }

  //编程按钮区域
  Widget _programArea() {
    return Positioned(
      left: ScreenUtil().setWidth(100.0),
      right: ScreenUtil().setWidth(60.0),
      top: ScreenUtil().setHeight(200.0),
      height: ScreenUtil().setHeight(300.0),
      child: Container(
          child: Row(
        children: <Widget>[
          _addBtn(),
          Expanded(
            child: _recordList(),
          ),
        ],
      )),
    );
  }

  //增加按钮及记录列表
  Widget _recordList() {
    return ListView.separated(
      padding: const EdgeInsets.only(left: 0),
      scrollDirection: Axis.horizontal,
      itemCount: programEntryList?.length ?? 0,
      separatorBuilder: (context, index) => const Divider(endIndent: 20),
      itemBuilder: (context, index) {
        ProgramEntity entity = programEntryList![index];
        return GestureDetector(
          onDoubleTap: () => _itemtDoubleClick(index),
          onTap: () => _itemClick(index),
          child: Container(
            width: ScreenUtil().setHeight(300.0),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius:
                    BorderRadius.circular(ScreenUtil().setWidth(20.0)),
                border: Border.all(
                    color: Colors.red, width: _selectIndex == index ? 2 : 0)),
            child: Column(children: [
              //编程截图
              _itemImage,
              //标题
              _itemTitle(entity.name ?? "prog"),
            ]),
          ),
        );
      },
    );
  }

  //编程图片
  final Widget _itemImage = Expanded(
    child: Container(
      child: ClipRRect(
        borderRadius: BorderRadius.all(
          Radius.circular(ScreenUtil().setWidth(20.0)),
        ),
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage('assets/programbackground.png'),
                fit: BoxFit.cover),
          ),
        ),
        //child: svg,
      ),
    ),
  );

  //编程标题
  Widget _itemTitle(String title) {
    return Container(
      height: ScreenUtil().setHeight(60.0),
      width: ScreenUtil().setHeight(300.0),
      decoration: BoxDecoration(
          color: Colors.blue[300],
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(ScreenUtil().setWidth(20.0)),
              bottomRight: Radius.circular(ScreenUtil().setWidth(20.0)))),
      child: Center(child: Text(title, style: _titleStyle)),
    );
  }

  Widget _addBtn() {
    return GestureDetector(
      onTap: _addClick,
      child: Container(
        // margin: EdgeInsets.only(right: 20),
        width: ScreenUtil().setHeight(300.0),
        height: ScreenUtil().setHeight(300.0),

        decoration: const BoxDecoration(
            image:
                DecorationImage(image: AssetImage('assets/program_add.png'))),
      ),
    );
  }

  //增加按钮事件处理
  void _addClick() {
    String id = timeIdStr();
    // int index =
    //     programEntryList!.isNotEmpty ? programEntryList!.last.index + 1 : 1;
    int index = 1;

    String name = 't_$index';
    ProgramEntity entity = ProgramEntity(
        id: id, name: name, index: index, filename: 'etst', txt: '');
    programEntryList!.add(entity);
    ProgramEntity.save(
        filename: widget.deviceEntity.name, entityList: programEntryList!);
    _selectIndex = programEntryList!.length - 1;

    _pushProgram(_selectIndex);
  }

  void _pushProgram(index) async {
    ProgramEntity entity = programEntryList![index];
    var programPage;
    switch (widget.deviceEntity.flag) {
      // case device.DeviceType.Serial2_0:
      //   programPage = ProgrameV2Page(programEntity: entity);
      //   break;
      // case device.DeviceType.Serial2_1:
      //   programPage = ProgrameV2Page(programEntity: entity);
      //   break;
      // case device.DeviceType.Serial3_0:
      //   programPage = ProgrameV3Page(programEntity: entity);
      //   break;
      // case device.DeviceType.Serial4_0:
      //   programPage = ProgrameV4Page(programEntity: entity);
      //   break;
      // case device.DeviceType.Serial6_0:
      //   programPage = ProgrameV6Page(programEntity: entity);
      //   break;
      // case device.DeviceType.Serial7_0:
      //   programPage = ProgrameV7Page(programEntity: entity);
      //   break;
      default:
        programPage = ProgramPage(programEntity: entity);
    }

    ProgramEntity entityname =
        await Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return programPage;
    }));

    //print('${entity.name}  filename= ${entity.filename} ');
    // if (entityname != null) {
    setState(() {
      //programEntryList[_selectIndex].name = entityname;
      //ProgramEntity.save();
      ProgramEntity.save(
          filename: widget.deviceEntity.name, entityList: programEntryList!);
    });
    // }
  }

  void _itemtDoubleClick(index) {
    //print('双击了$index');
    _selectIndex = index;
    _pushProgram(index);
  }

  void _itemClick(int index) {
    //print('点击了$index');
    if (index == _selectIndex) {
      _pushProgram(index);
    } else {
      setState(() {
        _selectIndex = index;
      });
    }
  }

  //返回按钮
  Widget _deleteBtn(BuildContext context) {
    return Positioned(
        right: ScreenUtil().setWidth(60.0),
        bottom: ScreenUtil().setHeight(120.0),
        width: ScreenUtil().setWidth(76.0),
        height: ScreenUtil().setHeight(81),
        child: CircleAvatar(
          radius: ScreenUtil().setWidth(42),
          backgroundColor: Colors.white,
          child: GestureDetector(
            onTap: _deleteClick,
            child: SizedBox(
              width: ScreenUtil().setWidth(38),
              child: Image.asset('assets/com_btn_delete.png'),
            ),
          ),
        ));
  }

  //删除按钮事件处理
  void _deleteClick() {
    debugPrint('点击了删除按钮');
    if (_selectIndex > -1 && _selectIndex < programEntryList!.length) {
      setState(() {
        programEntryList!.removeAt(_selectIndex);
        ProgramEntity.save(
            filename: widget.deviceEntity.name, entityList: programEntryList!);
      });
    }
  }
}
